package com.hdcircles.autoform.presenter;

import com.amap.api.location.AMapLocation;
import com.cengalabs.flatui.views.FlatEditText;
import com.google.gson.Gson;

import com.google.gson.JsonObject;
import com.hdcircles.autoform.app.Constants;
import com.hdcircles.autoform.base.RxPresenter;
import com.hdcircles.autoform.model.bean.ChooseQuestionBean;
import com.hdcircles.autoform.model.bean.FormBean;
import com.hdcircles.autoform.model.bean.MapData;
import com.hdcircles.autoform.model.bean.QuestionBean;
import com.hdcircles.autoform.model.http.ImageHelper;
import com.hdcircles.autoform.model.http.LocationHelper;
import com.hdcircles.autoform.model.http.HttpResponse;
import com.hdcircles.autoform.model.http.RetrofitHelper;
import com.hdcircles.autoform.presenter.contract.FormContract;
import com.hdcircles.autoform.util.LocationUtil;
import com.hdcircles.autoform.util.LogUtil;
import com.hdcircles.autoform.util.RxUtil;
import com.orhanobut.logger.Logger;

import java.util.List;

import javax.inject.Inject;

import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by hdcircles on 2016/10/15.
 */

public class FormPresenter extends RxPresenter<FormContract.View> implements FormContract.Presenter{



    private LocationHelper locationHelper;

    private RetrofitHelper retrofitHelper;

    private ImageHelper imageHelper;

    @Override
    public void detachView() {
        super.detachView();
        locationHelper.destroyLocation();
    }

    @Inject
    public FormPresenter(LocationHelper locationHelper,RetrofitHelper retrofitHelper,ImageHelper imageHelper){
        this.imageHelper=imageHelper;
        this.locationHelper=locationHelper;
        this.retrofitHelper=retrofitHelper;
    }


    @Override
    public void uploadImage(final String path, final QuestionBean questionBean, final boolean isLast) {
        Subscription subscription=retrofitHelper.getToken()
                .compose(RxUtil.<HttpResponse<String>>rxScheduleHelper())
                .compose(RxUtil.<String>handleResult())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        LogUtil.d(s);
                        imageHelper.uploadPicture(path,s);
                        imageHelper.setUploadListener(new ImageHelper.uploadListener() {
                            @Override
                            public void success(String url) {
                                questionBean.getPictureList().add(url);
                                questionBean.setPicture(new Gson().toJson(questionBean.getPictureList()));
                                Logger.json(questionBean.getPicture());
//                                if (isLast)
                                mView.notifyChange();
                            }
                        });
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtil.d(throwable.getMessage());
                        mView.showError("网络错误,请重新操作");
                    }
                });
        addSubscribe(subscription);
    }





    @Override
    public void getQuestion(String formId) {
        Subscription subscription=retrofitHelper.getQuestionByFormId(formId)
                .compose(RxUtil.<HttpResponse<List<QuestionBean>>>rxScheduleHelper())
                .compose(RxUtil.<List<QuestionBean>>handleResult())
                .subscribe(new Action1<List<QuestionBean>>() {
                    @Override
                    public void call(List<QuestionBean> questionBeanList) {
//                        for (QuestionBean questionBean:questionBeanList){
//                            questionBean.setForm_Id(null);
//                        }
                        mView.showQuestion(questionBeanList);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtil.d(throwable.getMessage());
                        mView.showError(throwable.getMessage());
                    }
                });
        addSubscribe(subscription);
    }

    @Override
    public void getChoose(final QuestionBean question) {
        Subscription subscription=retrofitHelper.getChooseBean(question.getId())
                .compose(RxUtil.<HttpResponse<List<ChooseQuestionBean>>>rxScheduleHelper())
                .compose(RxUtil.<List<ChooseQuestionBean>>handleResult())
                .subscribe(new Action1<List<ChooseQuestionBean>>() {
                    @Override
                    public void call(List<ChooseQuestionBean> chooseQuestionBeen) {
                        question.setChooseQuestion(chooseQuestionBeen);
                        mView.notifyChange();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mView.showError(throwable.getMessage());
                    }
                });
        addSubscribe(subscription);
    }

    @Override
    public boolean validate(List<QuestionBean> questionList) {
        for (QuestionBean bean:questionList){
            if (bean.isRequired()&&!bean.isCompleted()){
                mView.scrollToPosition(questionList.indexOf(bean));
                return false;
            }
        }
        return true;
    }

    @Override
    public void saveForm(FormBean form) {
        Subscription subscription=retrofitHelper.saveForm(form)
                .compose(RxUtil.<HttpResponse<String>>rxScheduleHelper())
                .compose(RxUtil.<String>handleResult())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        mView.saveFormSuccess();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mView.showError(throwable.getMessage());
                    }
                });
        addSubscribe(subscription);
    }



    @Override
    public void editFormData(FormBean originForm, List<QuestionBean> questionList) {
//        realmHelper.editQuestionList(originForm,questionList);
//        mView.saveFormSuccess();
        originForm.setQuestion(questionList);
        originForm.setTime(System.currentTimeMillis());
        Subscription subscription=retrofitHelper.updateForm(originForm)
                .compose(RxUtil.<HttpResponse<String>>rxScheduleHelper())
                .compose(RxUtil.<String>handleResult())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        mView.saveFormSuccess();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mView.showError(throwable.getMessage());
                    }
                });
        addSubscribe(subscription);
    }

    @Override
    public void getLocation(final FlatEditText view) {
        locationHelper.startLocation();
        locationHelper.setLocationListener(new LocationHelper.MapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation location) {
                if (null!=location){
                    if (location.getErrorCode()!=0) return;

                    //解析定位结果
                    String result= LocationUtil.getLocationStr(location);
                    LogUtil.d(result);
                    mView.showLocation(result,location.getAddress(),view);
                    locationHelper.stopLocation();
                }else {
                    mView.showError("定位失败");
                }
            }
        });
    }

    @Override
    public void createMapData(String tableId, String name,String address) {
        //TODO 生成 地址json
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("_name",name);
        jsonObject.addProperty("_address",address);
        Subscription subscription=retrofitHelper.createMapData(tableId,jsonObject.toString())
                .compose(RxUtil.<MapData>rxScheduleHelper())
                .subscribe(new Action1<MapData>() {
                    @Override
                    public void call(MapData mapData) {

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtil.e(throwable.getMessage());
                    }
                });
        addSubscribe(subscription);
    }
}
